/**
 * Cloneable接口：实现该接口的类可以被克隆，该类的clone方法必须重写
 * 当有基本数据类型时，为深拷贝，当有引用类型时，为浅拷贝
 * 如果要实现引用类型的深拷贝：见代码
 */
public class Test{
    public static void main(String[] args) throws CloneNotSupportedException {
        A a1 = new A("jack",23);
        A a2 = (A) a1.clone();// 这里的返回类型是Object，需要向下转型
//        System.out.println(a1);
//        System.out.println(a2);
//        System.out.println("===============");
        System.out.println(a1.b.m);
        System.out.println(a2.b.m);
        System.out.println("================");
        a1.b.m = 23;
        System.out.println(a1.b.m);
        System.out.println(a2.b.m);


    }
}
class A implements Cloneable{
    private String name;
    private int age;
    B b = new B();

    public A(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "name='" + name + '\'' + ", age=" + age;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        A temp = (A)super.clone();
        temp.b = (B)this.b.clone();
        return temp;
    }
}
class B implements Cloneable{
    int m = 12;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}